//
//  FZCoverLayerView.swift
//  MyWeiBo
//
//  Created by fangzhengwei on 2017/4/3.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit
import pop

class FZCoverLayerView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //回调的闭包
    var flagClosure : ((String)->())?
    //按钮数据数组
    
    fileprivate lazy var screenshotImg : UIImageView = {
       
        let imgView = UIImageView()
        
        imgView.image = self.loadScreenImg()?.applyLightEffect()
        
        return imgView
    }()
    
    fileprivate lazy var coverImg : UIImageView = {
       
        let imgView = UIImageView(image: UIImage(named: "compose_slogan"))
        return imgView
    }()
    
    fileprivate lazy var btnsArr : [FZComposeModel]? = {
    
        let arr = self.loadBtnsData()
        return arr
    }()
    fileprivate var coverLayerBtns : [FZCoverLayerButton] = [FZCoverLayerButton]()
    
    fileprivate lazy var removeButton : UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named : "tabbar_compose_background_icon_close"), for: .normal)
        btn.addTarget(self, action: #selector(removeBtn), for: .touchUpInside)
        return btn
    }()
    func setupUI(){
       
        frame.size = CGSize(width: screenWidth, height: screenHeight)

        addSubview(screenshotImg)
        addSubview(coverImg)
        addSubview(removeButton)
        
        screenshotImg.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        coverImg.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(120)
        }
        removeButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-20)
        }
        
        loadSixButton()
        
        popAnimation(isUP: true)
        
        
    }
    
    func loadSixButton() {
        //列数
        let col = 3
        let btnWidth : CGFloat = 80
        let btnHeight : CGFloat = 110
        let btnMargin : CGFloat = (screenWidth - CGFloat(col) * btnWidth) / 4
        for i in 0 ..< 6 {
            
           //计算列的索引
        let colIndex = i % col
            // 行 的索引
        let rowIndex = i / col
        print(colIndex , rowIndex)
            
        let btnX = CGFloat(colIndex) * btnWidth + CGFloat(colIndex + 1) * btnMargin
        let btnY = CGFloat(rowIndex) * btnHeight + CGFloat(rowIndex) * btnMargin
            
        let btn = FZCoverLayerButton()
        let model = btnsArr?[i]
        //标记tag值
        btn.tag = i
        btn.frame = CGRect(x: btnX, y: btnY + screenHeight, width: btnWidth, height: btnHeight)
            
        btn.adjustsImageWhenHighlighted = false
        
        btn.addTarget(self, action: #selector(clickAnimation(sender:)), for: .touchUpInside)
        btn.setImage(UIImage(named : (model?.icon)!), for: .normal)
        
        btn.setTitle(model?.title, for: .normal)
        
        addSubview(btn)
        
        coverLayerBtns.append(btn)

       }
   }
    
    func popAnimation(isUP:Bool) {
        
        if isUP == false {
            
            coverLayerBtns = coverLayerBtns.reversed()
        }
        
        for (index , value) in coverLayerBtns.enumerated() {
            
           let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            
            if isUP {
                
                anim?.toValue = CGPoint(x: value.centerX, y: value.centerY - 350)
                
            }else{
                
                anim?.toValue = CGPoint(x: value.centerX, y: value.centerY + 350)
            }
            anim?.springBounciness = 10
            
            anim?.springSpeed = 10
            
            anim?.beginTime = CACurrentMediaTime() + 0.035 * Double(index)
            
            value.pop_add(anim, forKey: nil)
            
        }
    }
    
    //加载按钮的plist数据
   fileprivate func loadBtnsData() -> [FZComposeModel]? {
    
      let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)
      guard let dataPath = path else {
         return nil
      }
    
      let source = NSArray(contentsOfFile: dataPath)
    
      guard let sourceArr = source else {
         return nil
      }
    
      let btnsDataArr = NSArray.yy_modelArray(with: FZComposeModel.self, json: sourceArr) as! [FZComposeModel]
    
      return btnsDataArr
    }
    
}

extension FZCoverLayerView {
    
   fileprivate func loadScreenImg()-> UIImage? {
        
        let window = UIApplication.shared.keyWindow!
        
        UIGraphicsBeginImageContext(window.bounds.size)
        
        window.drawHierarchy(in:CGRect(origin: CGPoint.zero, size: window.bounds.size), afterScreenUpdates: false)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
    
        return image
    }

 @objc fileprivate func clickAnimation(sender : UIButton) {
    
        //根据tag值获取模型
        let btnsModel = btnsArr?[sender.tag]
        
        UIView.animate(withDuration: 0.25, animations: {
            
            for button in self.coverLayerBtns{
                
                if button == sender {
                    
                    button.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
                }else{
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
        }) { (_) in
            
            UIView.animate(withDuration: 0.25, animations: {
                for btn in self.coverLayerBtns{
                    
                    btn.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                //跳转控制器
                self.flagClosure?((btnsModel?.className)!)
                self.removeFromSuperview()
            })
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        removeAnimation()
    }
    
    func removeBtn() {
        
        removeAnimation()
    }
    
   fileprivate func removeAnimation() {
        popAnimation(isUP: false)
        
        UIView.animate(withDuration: 0.25, animations: {
            self.removeButton.transform = CGAffineTransform(rotationAngle: -CGFloat(M_2_PI))
            
        }) { (_) in
            self.removeButton.alpha = 0
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
            
            self.removeFromSuperview()
        }
    }
}












